package org.example.spring_blog.controller;

import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.example.spring_blog.Constant.Constants;
import org.example.spring_blog.model.BlogInfo;
import org.example.spring_blog.service.BlogService;
import org.example.spring_blog.utils.JWTUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@Slf4j
@RequestMapping("/blog")
@RestController
public class BlogController {
    @Autowired
    private BlogService blogService;

    @RequestMapping("/getList")
    public List<BlogInfo> getList(){
        log.info("获取博客列表..");
        return blogService.getList();
    }

    @RequestMapping("/getBlog/Detail")
    public BlogInfo getBlogDetail(Integer blogId, HttpServletRequest request){
        log.info("getBlogDetail,blogId:{}",blogId);
        BlogInfo blogDetail = blogService.getBlogDetail(blogId);

        //从Request中获取token
        String token = request.getHeader(Constants.REQUEST_HEADER_TOKEN);
        Integer userId = JWTUtils.getIdByToken(token);

        //判断作者是否为登录用户
        if(userId != null && userId == blogDetail.getUserId()){
            blogDetail.setLoginUser(true);
        } else {
            blogDetail.setLoginUser(false);
        }

        return blogDetail;
    }

    @RequestMapping("/add")
    public Boolean addBlog(@RequestBody BlogInfo blogInfo, HttpServletRequest request) {
        log.info("添加博客,blogInfo:{}",blogInfo);

        if(!StringUtils.hasLength(blogInfo.getTitle()) || StringUtils.hasLength((blogInfo.getContent()))){
            return false;
        }
        //获取token
        String token = request.getHeader(Constants.REQUEST_HEADER_TOKEN);

        //从toke中获取登录用户的ID
        Integer userId = JWTUtils.getIdByToken(token);
        if(userId == null || userId < 0){
            return false;
        }
        blogInfo.setUserId(userId);

        return blogService.insertBlog(blogInfo);
    }

    @RequestMapping("/update")
    public Boolean updateBlog(BlogInfo blogInfo){
        log.info("更新博客,blogInfo:{}",blogInfo);
        if(blogInfo.getId() == null
                || !StringUtils.hasLength(blogInfo.getTitle())
                || !StringUtils.hasLength(blogInfo.getContent())){
            return false;
        }

        blogService.updateBlog(blogInfo);

        return true;
    }

    @RequestMapping("delete")
    public Boolean delete(Integer blogId){
        log.info("删除博客, blogId:{}", blogId);
        if (blogId<=0){
            return false;
        }
        BlogInfo blogInfo = new BlogInfo();
        blogInfo.setDeleteFlag(1);
        blogService.updateBlog(blogInfo);

        return true;
    }


}
